package com.app.couponsharelife.ui.view

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import androidx.constraintlayout.widget.ConstraintLayout
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.TranslateAnimation
import android.widget.RelativeLayout
import com.app.couponsharelife.R
import com.app.couponsharelife.data.bean.CouponMoneyBean
import com.app.couponsharelife.utils.AppUtils
import kotlinx.android.synthetic.main.diamond_view_item.view.*
import java.util.*

class DiamondsContainer : RelativeLayout, View.OnClickListener {

    private val ANIMATION_TIME: Long = 1000

    private val ANIMATION_DEFAULT_TIME: Long = 1000

    private val mViews = arrayListOf<View>()

    private var totalData: MutableList<Any> = mutableListOf()//所有钻石

    private var alreadyData: MutableList<Any> = mutableListOf()//已经显示的钻石

    private var remainData: MutableList<Any> = mutableListOf()//还没显示的钻石

    private var randomIndexList = mutableListOf<Int>()

    private var parentWidth: Int = 0

    private var parentHeight: Int = 0

    private var defaultDiamondView: View? = null

    private var mWindowWidth = 0

    private var areaWidth = 0

    private var areaHeight = 0

    private var mMaxNum = 9

    var listener: com.app.couponsharelife.ui.listener.OnClickListener? = null

    constructor(context: Context) : super(context, null) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs, 0) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {
        mWindowWidth = AppUtils.getDisplayMetrics(context).widthPixels
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        parentWidth = measuredWidth
        parentHeight = measuredHeight
    }

    //0.085~0.14
    private fun addDefaultDiamondView() {
        defaultDiamondView = LayoutInflater.from(context).inflate(R.layout.diamond_view_item, this, false)
        val width = (mWindowWidth * (Math.random() * 55 + 85) / 1000).toInt()
        val layoutParams1 = ConstraintLayout.LayoutParams(width, width)
        layoutParams1.startToStart = R.id.clDiamond
        layoutParams1.endToEnd = R.id.clDiamond
        defaultDiamondView!!.ivDiamond.layoutParams = layoutParams1
        val layoutParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT)
        addView(defaultDiamondView, layoutParams)

        //设置动画
        initAnim(defaultDiamondView!!)
        //设置上下抖动的动画
        initFloatAnim(defaultDiamondView!!)
    }

    private fun addDataDiamondView() {
        areaWidth = parentWidth / 2
        areaHeight = parentHeight / 4

        alreadyData.clear()
        val size = if (remainData.size < mMaxNum) remainData.size else mMaxNum
        calculateRandomIndex(size)
        for (i in 0 until size) {//限制一屏个数
            val diamondView = LayoutInflater.from(context).inflate(R.layout.diamond_view_item, this, false)
            diamondView.tvDiamond.text = (remainData[i] as CouponMoneyBean.ListBean).value
//            diamondView.tvBubble.text = (remainData[i] as FirstTaskBean.DiamondBean).credit2
            val width = (mWindowWidth * (Math.random() * 55 + 85) / 1000).toInt()
            val layoutParams = ConstraintLayout.LayoutParams(width, width)
            layoutParams.startToStart = R.id.clDiamond
            layoutParams.endToEnd = R.id.clDiamond
            diamondView.ivDiamond.layoutParams = layoutParams
            diamondView.measure(0, 0)

            setChildViewPosition(diamondView, i)
            diamondView.tag = i
            diamondView.setOnClickListener(this)
            //设置动画
            initAnim(diamondView)
            //设置上下抖动的动画
            initFloatAnim(diamondView)
            mViews.add(diamondView)
            addView(diamondView)
            alreadyData.add(remainData[i])
        }
        remainData.subList(0, size).clear()
    }

    /**
     * 生成随机位置
     */
    private fun calculateRandomIndex(size: Int) {
        randomIndexList.clear()
        for (i in 1 until size) {
            randomIndexList.add(i)
        }
        randomIndexList.shuffle()
    }

    override fun onClick(v: View?) {
        if (v != null && canClick) {
            mViews.remove(v)
            animRemoveView(v)
            if (alreadyData.size > (v.tag as Int)) {
                listener?.click(v.tag as Int, alreadyData[v.tag as Int])
            }
            if (mViews.size == 0) {
                if (remainData.isEmpty()) {
                    setData(arrayListOf(), 0)
                } else
                    addDataDiamondView()
            }
        } else listener?.click(-1, "请勿快速点击")
    }

    private fun animRemoveView(view: View) {
        val animator = ValueAnimator.ofFloat(parentHeight.toFloat(), 0f)
        animator.duration = 2000
        animator.interpolator = LinearInterpolator()

        //动画更新的监听
        animator.addUpdateListener { animation ->
            val value = animation.animatedValue as Float
//            Log.d("guluwa", "onAnimationUpdate: " + view.translationY)
//            Log.d("guluwa", "onAnimationUpdate: " + view.y)
            view.alpha = value / parentHeight
            view.translationY = view.y - (parentHeight - value)
        }
        animator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                removeView(view)
            }
        })
        animator.start()
    }

    //设置子view的位置
    private fun setChildViewPosition(childView: View, index: Int) {
        //设置随机位置
        val x = calculateXPosition(childView, index)
        val y = calculateYPosition(childView, index)

//        Log.d("guluwa", "setChildViewPosition: parentWidth=$parentWidth,parentHeight=$parentHeight")
//        Log.d("guluwa", "setChildViewPosition: childWidth=" + childView.measuredWidth + ",childHeight=" + childView.measuredHeight)
        if (mViews.isNotEmpty() && calculatePositionRepeat(mViews[0], childView, x, y)) {
            setChildViewPosition(childView, index)
        } else {
            childView.x = x
            childView.y = y
//            Log.d("guluwa", "setChildViewPosition: x=${x},y=${y}")
        }
    }

    private fun calculateXPosition(childView: View, index: Int): Float {
        return if (index == 0) {
            (parentWidth - childView.measuredWidth) / 2f
        } else {
            val randomX = Random().nextFloat()
            var dis = areaWidth - childView.measuredWidth
            dis = if (dis < 0) 0 else dis
            when (randomIndexList[index - 1]) {
                1, 5, 8, 4 -> {
                    randomX * dis
                }
                else -> {
                    areaWidth + randomX * dis
                }
            }
        }
    }

    private fun calculateYPosition(childView: View, index: Int): Float {
        return if (index == 0) {
            (parentHeight - childView.measuredHeight) / 2f
        } else {
            val randomY = Random().nextFloat()
            var dis = areaHeight - childView.measuredHeight
            dis = if (dis < 0) 0 else dis
            when (randomIndexList[index - 1]) {
                1, 3 -> {
                    randomY * dis
                }
                5, 7 -> {
                    areaHeight + randomY * dis
                }
                8, 6 -> {
                    2 * areaHeight + randomY * dis
                }
                else -> {
                    3 * areaHeight + randomY * dis
                }
            }
        }
    }

    private fun calculatePositionRepeat(view: View, childView: View, x: Float, y: Float): Boolean {
        return (view.x + view.measuredWidth > x
                && x + childView.measuredWidth > view.x
                && view.y + view.measuredHeight > y
                && y + childView.measuredHeight > view.y)
    }

    //FloatView上下抖动的动画
    private fun initFloatAnim(view: View) {
        val anim = TranslateAnimation(0f, 0f, -10f, 10f)
        anim.interpolator = AccelerateDecelerateInterpolator()
        anim.duration = ANIMATION_TIME
        anim.repeatCount = Integer.MAX_VALUE
        anim.repeatMode = Animation.REVERSE//反方向执行
        view.startAnimation(anim)
    }

    //FloatView初始化时动画
    private fun initAnim(view: View) {
        view.alpha = 0f
        view.scaleX = 0f
        view.scaleY = 0f
        view.animate().alpha(1f).scaleX(1f).scaleY(1f).setDuration(ANIMATION_DEFAULT_TIME).start()
    }

    fun setData(list: List<Any>, status: Int) {
        //使用post方法确保在UI加载完的情况下 调用init() 避免获取到的宽高为0
        if (status != 0) {
            if (defaultDiamondView != null) {
                defaultDiamondView!!.clearAnimation()
                removeView(defaultDiamondView)
                defaultDiamondView = null
            }
            for (view in mViews) {
                view.clearAnimation()
                removeView(view)
            }
            mViews.clear()
            alreadyData.clear()
            totalData.clear()
            totalData.addAll(list)
            remainData.clear()
            remainData.addAll(list)
            addDataDiamondView()
        } else {
            if (defaultDiamondView == null) {
                addDefaultDiamondView()
            } else {
                defaultDiamondView?.clearAnimation()
                initFloatAnim(defaultDiamondView!!)
            }
            defaultDiamondView!!.visibility = View.VISIBLE
        }
    }

    var canClick = true

    override fun onTouchEvent(ev: MotionEvent): Boolean {
        return if (this.canClick) {
            super.onTouchEvent(ev)
        } else {
            false
        }
    }
}